
package com.sci;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;


public class Cmd
{
	public interface Callback
	{
		void onCallback(String data);
	}
	
	public static String execute(String[] command, String charset) throws IOException
	{
		return execute(command, charset, null);
	}
	
	public static String execute(String[] command, String charset, Callback callback) throws IOException
	{
		return execute(Arrays.asList(command), charset, callback);
	}
	
	public static String execute(List<String> command, String charset) throws IOException
	{
		return execute(command, charset, null);
	}
	
	public static String execute(List<String> command, String charset, Callback callback) throws IOException
	{
		StringBuffer sb = new StringBuffer();
		ProcessBuilder builder = new ProcessBuilder(command);
		builder.redirectErrorStream(true);
		Process process = builder.start();
		BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), charset));
		String line;
		while ((line = reader.readLine()) != null)
		{
			sb.append(line);
			if (callback != null)
			{
				callback.onCallback(line);
			}
		}
		reader.close();
		return sb.toString();
	}
}
